package cn.innosmart.aq.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.tutk.p2p.ConnectionEntity;
import com.tutk.p2p.ConnectionManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.LanSearchResultAdapter;
import cn.innosmart.aq.camera.GetLanDeviceTask;
import cn.innosmart.aq.camera.models.CameraBean;
import cn.innosmart.aq.customize.CustomsizeDialog;
import cn.innosmart.aq.customize.InfoDialog;
import cn.innosmart.aq.manager.CameraManager;
import cn.innosmart.aq.util.INetworkInteractUtil;
import cn.innosmart.aq.util.NetworkInteractUtil;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.view.activity.base.BaseActivity;
import cn.innosmart.qrcode.view.CaptureActivity;

/**
 * 添加摄像头界面
 * Created by David on 2015/7/14.
 */
public class AddCameraActivity extends BaseActivity implements INetworkInteractUtil {
    private final int EXIT = 2;
    private final int CANCEL = -1;
    private final int ADDCAMERA = 1;
    //    private final int ADDBOXBYLANSEARCH = 6;
    private final int MODIFYCAMERA = 2;
    private final int RESULTCODE_BACKPRESSED = -1;
    private final int REQUESTCODE_QRCODE = 5;
    private EditText etCameraName;
    private EditText etCameraUid;
    private EditText etCameraPassword;
    private Button btAdd;
    private Button btRemove;
    private int flag;
    private NetworkInteractUtil interactUtil;
    private ConnectionEntity connectionEntity;
    /**
     * 设置界面Toolbar
     */
    private Toolbar toolbar;
    private CameraBean cameraBean;
    private View.OnClickListener mBtnOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (etCameraName.getText().toString().trim().equals("")) {
                showToast(getString(R.string.name_can_not_empty));
                return;
            }
            if (etCameraUid.getText().toString().trim().equals("")) {
                showToast(getString(R.string.uid_can_not_empty));
                return;
            }
            if (etCameraPassword.getText().toString().trim().equals("")) {
                showToast(getString(R.string.password_can_not_empty));
                return;
            }
            if (cameraBean == null) {
                cameraBean = new CameraBean();
            }
            String title = etCameraName.getText().toString().trim();
            String uid = etCameraUid.getText().toString().trim();
            if (checkRepeatTitle(title)) {
                showToast(getString(R.string.name_had_used));
                return;
            }
            if (checkRepeatUid(uid)) {
                showToast(getString(R.string.uid_had_been_used));
                return;
            }
            cameraBean.setTitle(title);
            cameraBean.setPsd(etCameraPassword.getText().toString().trim());
            cameraBean.setUid(etCameraUid.getText().toString().trim());
            cameraBean.setPlace(SystemConstant.currentAquariumBean.getId());

            if (flag == ADDCAMERA) {
                CameraManager.getInstance().Register(connectionEntity, cameraBean.toAddParam(), new CameraManager.RegisterCallBack() {
                    @Override
                    public void onRegisterResponseCallBack(int ret, String cameraid) {
                        if (ret == 0) {
                            System.out.println("cameraid=" + cameraid);
                            cameraBean.setId(cameraid);
                            SystemConstant.currentAquariumBean.getCameras().add(cameraBean.getUid());
                            SystemConstant.cameraBeanHashMap.put(cameraBean.getUid(), cameraBean);
                            exit();
                        } else if (ret == -1) {
                            showToast(getString(R.string.camera_has_added));
                        }

                    }
                });
            } else if (flag == MODIFYCAMERA) {
                CameraManager.getInstance().Update(connectionEntity, cameraBean.toUpdateParam(), new CameraManager.UpdateCallBack() {
                    @Override
                    public void onUpdateResponseCallBack(int ret) {
                        if (ret == 0) {
                            showToast(getString(R.string.activity_add_camera_modify_success));
                            SystemConstant.cameraBeanHashMap.put(cameraBean.getUid(), cameraBean);
                            Intent intent = getIntent();
                            intent.putExtra("CAMID", cameraBean.getUid());
                            System.out.println("CAMID=" + cameraBean.getUid());
                            setResult(0x002, intent);
                            exit();
                        } else if (ret == -1) {
                            showToast(getString(R.string.activity_add_camera_modify_failed));
                        }
                    }
                });
            }


//            if (flag == ADDCAMERA || flag == ADDBOXBYLANSEARCH) {
////                syncAddBox();
//            } else if (flag == MODIFYBOX) {
//                Intent intent = new Intent();
//                intent.putExtra("position", getIntent().getIntExtra("position", -1));
//                intent.putExtra("BoxBean", boxbean);
//                syncModifyBox(boxbean);
//                setResult(MODIFYBOX, intent);
//                showLoadingDialog(AddCameraActivity.this, "同步中...");
//            }
        }
    };
    private View.OnClickListener onNavigationClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setResult(CANCEL);
            finish();
            overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
        }
    };
    private ArrayList<String> resultList = new ArrayList<>();
    private MenuItem mProgressMenu;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    setLoadingState(true);
                    break;
                case 1:
                    setLoadingState(false);
                    break;
                case EXIT:
                    exit();
                    break;
            }
        }
    };
    //    private List<GetLanDeviceTask.LANSearchResult> resultList;
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_delete:
                    deleteAlert(cameraBean);
                    break;
                case R.id.action_search:
                    searchCamera();
                    break;
                case R.id.action_qrcode:
                    Intent qrcodeIntent = new Intent(AddCameraActivity.this, CaptureActivity.class);
                    startActivityForResult(qrcodeIntent, REQUESTCODE_QRCODE);
                    break;
            }
            return true;
        }


        private void searchCamera() {
            mHandler.sendEmptyMessage(0);
            new GetLanDeviceTask() {
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                }

                @Override
                protected void onPostExecute(List<LANSearchResult> lanResults) {
                    super.onPostExecute(lanResults);
                    resultList.clear();
                    if (lanResults != null) {
                        if (lanResults.size() == 0) {
//                            showToast(getString(R.string.no_search_result));
                        } else {
//                            showToast("lanResults.Size" + lanResults.size());
                            for (LANSearchResult lanSearchResult : lanResults) {
                                resultList.add(lanSearchResult.uid);
                            }
                        }
                        mHandler.sendEmptyMessage(1);
                    }

//                    mSearchResults = lanResults;
//                    if (mSearchResults.size() == 0) {
//                        showToast("");
//                        activity.showToast(R.string.add_gateway_no_lan_device_found);
//                    } else {
//                        adapter.notifyDataSetChanged();
//                    }
                }
            }.executeOnExecutor(Executors.newCachedThreadPool());
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUESTCODE_QRCODE) {
            if (resultCode == RESULT_OK) {
                String result = data.getStringExtra("QRCODERESULT");
                etCameraUid.setText(result);
            } else if (resultCode == RESULTCODE_BACKPRESSED) {
            }
        }
    }

    private void assignViews() {
        etCameraName = (EditText) findViewById(R.id.et_username);
        etCameraUid = (EditText) findViewById(R.id.et_boxuid);
        etCameraPassword = (EditText) findViewById(R.id.et_boxpassword);
        btAdd = (Button) findViewById(R.id.bt_add);
        btRemove = (Button) findViewById(R.id.bt_remove);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_camera);
        assignViews();
        interactUtil = new NetworkInteractUtil(this);
        flag = getIntent().getIntExtra("flag", -1);
        connectionEntity = ConnectionManager.getInstance().getCurrentConnectionEntity();
        setBar(flag);
        setData(flag);

        if (flag == MODIFYCAMERA) {
            etCameraUid.setEnabled(false);
            btRemove.setVisibility(View.VISIBLE);
            btRemove.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    deleteAlert(cameraBean);
                    Toast.makeText(view.getContext(), R.string.enter_device_manger_to_remove_camera, Toast.LENGTH_LONG).show();
                }
            });

        }
    }

//    private void syncAddBox() {
//        if (cameraBean.isSynced()) {
//            return;
//        }
//        JSONObject jsonParam = new JSONObject();
//        JSONObject jsonDevice = new JSONObject();
//        try {
//            jsonDevice.put("did", boxbean.getUid());
//            jsonDevice.put("username", boxbean.getUsername());
//            jsonDevice.put("password", boxbean.getPassword());
//            jsonDevice.put("alias", boxbean.getTitle());
//            jsonParam.put("device", jsonDevice);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        interactUtil.syncAddBox(jsonParam);
//    }

    private void setBar(int flag) {
        toolbar = (Toolbar) findViewById(R.id.toolbar);

        ((ImageView) findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        toolbar.setTitle("");
        if (flag == ADDCAMERA) {
            //添加Box
            ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.activity_add_camera_add_camera));
        } else if (flag == MODIFYCAMERA) {
            //修改Box
            ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.activity_add_camera_modify_camera));
        } else {
            //添加Box
            ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.activity_add_camera_add_camera));
        }
        setSupportActionBar(toolbar);
//        toolbar.setNavigationOnClickListener(onNavigationClickListener);
        findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(CANCEL);
                finish();
                overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
            }
        });
        toolbar.setOnMenuItemClickListener(onMenuItemClick);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    private void setData(int flag) {
        if (flag == ADDCAMERA) {
            //添加Box
            String uid = getIntent().getStringExtra("uid");
            if (!TextUtils.isEmpty(uid)) {
                etCameraUid.setText(uid);
            }
            btAdd.setText(getString(R.string.save));
        } else if (flag == MODIFYCAMERA) {
            //修改Box
            Intent intent = getIntent();
            cameraBean = SystemConstant.cameraBeanHashMap.get(intent.getStringExtra("CamUid"));
            etCameraName.setText(cameraBean.getTitle());
            etCameraUid.setText(cameraBean.getUid());
            etCameraPassword.setText(cameraBean.getPsd());
            btAdd.setText(getString(R.string.save));
        } else {
            //添加Box
            String uid = getIntent().getStringExtra("uid");
            if (!TextUtils.isEmpty(uid)) {
                etCameraUid.setText(uid);
            }
            btAdd.setText(getString(R.string.save));
        }
        btAdd.setOnClickListener(mBtnOnClickListener);
    }

    private boolean checkRepeatTitle(String title) {
        if (flag == ADDCAMERA) {
            ArrayList<String> cameraBeens = SystemConstant.currentAquariumBean.getCameras();
            for (String uid : cameraBeens) {
                CameraBean cameraBean = SystemConstant.cameraBeanHashMap.get(uid);
                if (cameraBean != null)
                    if (title.equals(cameraBean.getTitle())) {
                        return true;
                    }
            }
            //检查重复的名称
        } else if (flag == MODIFYCAMERA) {
            ArrayList<String> cameraBeens = SystemConstant.currentAquariumBean.getCameras();
            for (String uid : cameraBeens) {
                if (uid.equals(cameraBean.getUid()))
                    continue;
                CameraBean cameraBean = SystemConstant.cameraBeanHashMap.get(uid);
                if (cameraBean != null)
                    if (title.equals(cameraBean.getTitle())) {
                        return true;
                    }
            }
        }
        return false;
    }

    private boolean checkRepeatUid(String uids) {
        if (flag == ADDCAMERA) {
            ArrayList<String> cameraBeens = SystemConstant.currentAquariumBean.getCameras();
            for (String uid : cameraBeens) {
                CameraBean cameraBean = SystemConstant.cameraBeanHashMap.get(uid);
                if (cameraBean != null)
                    if (uids.equals(cameraBean.getUid())) {
                        return true;
                    }
            }
            //检查重复的名称
        } else if (flag == MODIFYCAMERA) {
            ArrayList<String> cameraBeens = SystemConstant.currentAquariumBean.getCameras();
            for (String uid : cameraBeens) {
                if (uid.equals(cameraBean.getUid()))
                    continue;
                CameraBean cameraBean = SystemConstant.cameraBeanHashMap.get(uid);
                if (cameraBean != null)
                    if (uids.equals(cameraBean.getUid())) {
                        return true;
                    }
            }
        }
        return false;
    }

    @Override
    protected void onResume() {
        setBaseDialogContext(this);
        super.onResume();
        toolbar.setNavigationIcon(null);
    }

    public void setLoadingState(boolean refreshing) {
        if (mProgressMenu != null) {
            if (refreshing) {
                mProgressMenu.setActionView(R.layout.actionbar_indeterminate_progress);
                mProgressMenu.setVisible(true);
                showLoadingDialog(AddCameraActivity.this, getString(R.string.searching));
            } else {
//                mProgressMenu.setVisible(false);
                mProgressMenu.setActionView(null);
                hideLoadingDialog();
                showSearchResultDialog();
            }
        } else {
        }
    }

    private void showSearchResultDialog() {
        final CustomsizeDialog customsizeDialog = new CustomsizeDialog(AddCameraActivity.this);
        customsizeDialog.setTitle(getString(R.string.dialog_title_search_result));
        customsizeDialog.setListviewAdapter(new LanSearchResultAdapter(this, resultList));
        customsizeDialog.setPositiveButton(getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (resultList.size() != 0)
                    etCameraUid.setText(resultList.get(customsizeDialog.getChoosenPosition()));
                customsizeDialog.dismiss();
            }
        });
        customsizeDialog.show();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_toolbar_modify_box, menu);
        mProgressMenu = menu.findItem(R.id.action_search);
        if (flag == ADDCAMERA) {
            menu.findItem(R.id.action_qrcode).setVisible(true);
            menu.findItem(R.id.action_delete).setVisible(false);
            menu.findItem(R.id.action_search).setVisible(true);
        } else if (flag == MODIFYCAMERA) {
            menu.findItem(R.id.action_search).setVisible(false);
            menu.findItem(R.id.action_delete).setVisible(false);
        }
        return true;
    }

    /**
     * 删除提示
     */
    private void deleteAlert(final CameraBean cameraBean) {
        final InfoDialog delateAlertDialog = new InfoDialog(AddCameraActivity.this);
        delateAlertDialog.setTitle(getString(R.string.dialog_title_alert));
        delateAlertDialog.setContent(String.format(getString(R.string.dialog_content_delete_sure), cameraBean.getTitle()));
        delateAlertDialog.setNegativeButton(getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delateAlertDialog.dismiss();
            }
        });
        delateAlertDialog.setPositiveButton(getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delateAlertDialog.dismiss();
                showLoadingDialog(AddCameraActivity.this, "删除中");
                CameraManager.getInstance().Remove(connectionEntity, cameraBean.toRemoveParam(), new CameraManager.RemoveCallBack() {
                    @Override
                    public void onRemoveResponseCallBack(int ret) {
                        hideLoadingDialog();
                        if (ret == 0) {
                            SystemConstant.cameraBeanHashMap.remove(cameraBean.getUid());
                            for (int i = 0; i < SystemConstant.currentAquariumBean.getCameras().size(); i++) {
                                if (cameraBean.getUid().equals(SystemConstant.currentAquariumBean.getCameras().get(i))) {
                                    SystemConstant.currentAquariumBean.getCameras().remove(i);
                                }
                            }
                            exit();
                        } else {
                            showToast("删除失败!");
                        }
                    }
                });

            }
        });
        delateAlertDialog.show();
    }


    @Override
    public void onNetworkInteractAllOver(int ret) {

    }

    @Override
    public void onNetworkInteractOver(int ret, String flag, Object object) {
        if (flag.equals(interactUtil.SYNCADDBOX)) {
            if (ret == 0) {
                JSONObject response = (JSONObject) object;
                int code = -1;
                String hubId = null;
                try {
                    code = response.getInt("code");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    if (code == 0) {
                        mHandler.sendEmptyMessage(EXIT);
                    } else if (code == 1) {
                        showToast(getString(R.string.box_has_added));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (ret == -1) {
                hideLoadingDialog();
            }
        }
    }
}
